/**
 *  json响应处理
 */

const document = require("./document.js");

const getResultJsonStr = (code = -1, data = "", msg = "", page = {}) => {
  if (Object.keys(page).length) {
    return {
      status: code === 200 ? "ok" : "error",
      msg: msg || document.list[code] || document.list[-1],
      code,
      data,
      page,
    };
  } else {
    return {
      status: code === 200 ? "ok" : "error",
      msg: msg || document.list[code] || document.list[-1],
      code,
      data,
    };
  }
};

const sendJson = (response, json) => {
  response.writeHead(200, {
    "Access-Control-Allow-Headers":
      "token,Content-Type,Content-Length, Authorization, Accept,X-Requested-With,domain,zdy",
    "Access-Control-Allow-Methods": "POST,GET,OPTIONS",
    "Access-Control-Allow-Credentials": true,
    "Content-Type": "text/html;charset:utf-8",
  });
  response.end(JSON.stringify(json));
};

const sendResult = (response, code = -1, data = "", msg = "", page) => {
  sendJson(response, getResultJsonStr(code, data, msg, page));
};

module.exports = {
  getResultJsonStr: getResultJsonStr,
  sendJson: sendJson,
  sendResult: sendResult,
};
